from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import zmq
import pickle

class ZeroMQReceiver(QThread):
	"""A listener receive sequence information from Cicero"""
	REQUEST_TIMEOUT = 2000
	messageOut = pyqtSignal(dict)

	def __init__(self,port=6666):
		super(ZeroMQReceiver, self).__init__()
		self.port = port
		self.context = zmq.Context()

		self.keep_running = False
		self.commands = {}



	def bindAddress(self):
		self.socket = self.context.socket(zmq.REP)
		self.socket.bind("tcp://*:%d" % self.port)

	def closeSocket(self):
		if hasattr(self,'socket') == False:
			return
		self.socket.setsockopt(zmq.LINGER , 0)
		self.socket.close()

	def run(self):
		self.bindAddress()
		i=0
		while(self.keep_running):
			if (self.socket.poll(self.REQUEST_TIMEOUT) & zmq.POLLIN) != 0:
				i = i+1
				print(i)
				message = self.socket.recv()
				self.socket.send_string("Have Received Image")
				self.message=pickle.loads(message)
				command = self.message
				self.messageOut.emit(command)

		self.closeSocket()

if __name__ == '__main__':
	app = QApplication([])

	listener = ZeroMQReceiver(port = 6666)
	def print_sig(command):
		print(listener.message)

	listener.messageOut.connect(print_sig)

	listener.keep_running = True
	listener.start()

	app.exec_()

